package own.test.service.impl;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;

import own.test.service.ActiveMqReceiveService;
import own.test.service.DateService;

public class ActiveMqReceiveServiceImpl implements ActiveMqReceiveService {

	@Autowired
	private JmsTemplate jmsTemplate;
	
	private DateService ds = new DateServiceImpl();
	
	@Override
	public String receive(Destination destination) {
		TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
        if (tm != null) {
            try {
                System.out.println("Get Message: " + tm.getText() + " from Destination " + destination.toString());
                return tm.getText();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
        return null;
	}

	@Override
	public String receive(String destination) {
		TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
        if (tm != null) {
            try {
                System.out.println("Get Message: " + tm.getText() + " from Destination " + destination.toString());
                return tm.getText();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
        return null;
	}
	
	@Override
	public String receive() {
		String destination = jmsTemplate.getDefaultDestinationName().toString();
		TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
        if (tm != null) {
            try {
                System.out.println(ds.getNowDateStr() +" 读取 " + destination+" 的来信："+tm.getText());
                return tm.getText();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
        return null;
	}

}
